package com.cn.appcore.utils

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.webkit.WebSettings
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.AppUtils
import com.cn.appcore.config.AppConfig
import java.io.File

/**
 * @author wxl
 * @date 2020/3/16
 * @desc
 */
object ApkUtil {

    /**
     * 安装Apk
     */
    fun installApk(context: Context, apk: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.action = Intent.ACTION_VIEW
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        val uri: Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context, context.packageName, apk)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            uri = Uri.fromFile(apk)
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        context.startActivity(intent)
    }

    /**
     * 获取当前app的升级版本号
     *
     * @param context 上下文
     */
    fun getVersionCode(context: Context): Long {
        return try {
            val packageManager = context.packageManager
            val packageInfo =
                packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.longVersionCode
        } catch (e: Exception) {
            e.printStackTrace()
            1
        }
    }

    /**
     * 获取当前app的版本号
     *
     * @param context 上下文
     */
    fun getVersionName(): String {
//        return try {
//            val packageManager = context.packageManager
//            val packageInfo =
//                packageManager.getPackageInfo(context.packageName, 0)
//            packageInfo.versionName
//        } catch (e: Exception) {
//            e.printStackTrace()
//            "1.0.0"
//        }
        val versionName = AppUtils.getAppVersionName()
//        return  "1.0.1"
        return  versionName
    }

    /**
     * 版本号比较
     * 前者等于后者则返回0  ==
     * 如果前者大于后者，返
     *  前者小于后者则返回-1
     *
     * compareTo()方法返回值为int类型，就是比较两个值，如：x.compareTo(y)。如果前者大于后者，返回1，前者等于后者则返回0，前者小于后者则返回-1
     */
    fun compareVersion(version1: String, version2: String): Int {
        var version1Array = version1.split(".")
        var version2Array = version2.split(".")
        var len1=version1Array.size
        var len2=version2Array.size
        var lim=Math.min(len1,len2)


        var i=0
        while (i < lim) {
            val c1 = if ("" == version1Array[i]) 0 else version1Array[i].toInt()
            val c2 = if ("" == version2Array[i]) 0 else version2Array[i].toInt()
            if (c1 != c2) {
                return c1 - c2;
            }
            i++;
        }
        return len1 - len2;
    }
    fun getUserAgent(): String? {
        var userAgent = ""
        userAgent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                WebSettings.getDefaultUserAgent(AppConfig.getApplication())
            } catch (e: java.lang.Exception) {
                System.getProperty("http.agent")
            }
        } else {
            System.getProperty("http.agent")
        }
        val sb = StringBuffer()
        var i = 0
        val length = userAgent.length
        while (i < length) {
            val c = userAgent[i]
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", c.toInt()))
            } else {
                sb.append(c)
            }
            i++
        }
        return sb.toString()
    }

    fun getChannelName(mContext: Context): String {
        var channelName = ""
        try {
            val packageManager = mContext.packageManager
            if (packageManager != null) {
                val applicationInfo = packageManager.getApplicationInfo(
                    mContext.packageName,
                    PackageManager.GET_META_DATA
                )
                if (applicationInfo.metaData != null) {
                    channelName = "${applicationInfo.metaData["UMENG_CHANNEL"]}"
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return channelName
    }
}